package com.module.overview.ui.cardHistoryDetails.provider

import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.utils.AppUtils.getString
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserAcLevel
import com.module.ble.repo.UserAcLevelRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.common48DataConvert
import com.module.ble.utils.groupAcLevelDataByValueAndTime
import com.module.ble.widget.CusPieChartView
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/14
 *
 * 描述：活动比例卡片
 *
 * 修订历史：完成度
 *
 */
class OvActivityRatioCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_ACTIVITY_DAY_RATIO,
    override val layoutId: Int = R.layout.overview_activity_ratio_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {


    private var pieChartView: CusPieChartView? = null

    private var curTime = time

    private var tvStrengthHigh: TextView? = null
    private var tvStrengthMedium: TextView? = null
    private var tvStrengthLow: TextView? = null
    private var tvStrengthInactive: TextView? = null

    private var tvStrengthHighValue: TextView? = null
    private var tvStrengthMediumValue: TextView? = null
    private var tvStrengthLowValue: TextView? = null
    private var tvStrengthInactiveValue: TextView? = null

    private var strengthHigh = 0L
    private var strengthMedium = 0L
    private var strengthLow = 0L
    private var strengthInactive = 0L

    init {
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        pieChartView = viewHolder.getView(R.id.pieChartView)
        tvStrengthHigh = viewHolder.getView(R.id.tvStrengthHigh)
        tvStrengthMedium = viewHolder.getView(R.id.tvStrengthMedium)
        tvStrengthLow = viewHolder.getView(R.id.tvStrengthLow)
        tvStrengthInactive = viewHolder.getView(R.id.tvStrengthInactive)

        tvStrengthHighValue = viewHolder.getView(R.id.tvStrengthHighValue)
        tvStrengthMediumValue = viewHolder.getView(R.id.tvStrengthMediumValue)
        tvStrengthLowValue = viewHolder.getView(R.id.tvStrengthLowValue)
        tvStrengthInactiveValue = viewHolder.getView(R.id.tvStrengthInactiveValue)

        super.onViewHolderCreated(viewHolder, viewType)
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {

        // 自定义圆环宽度
//        pieChartView?.setStrokeWidth(30f)

        // 设置起始角度（从顶部开始）
        pieChartView?.setStartAngle(-90f)

//        // 设置背景圆环颜色
//        pieChartView.setBackgroundColor(Color.parseColor("#F0F0F0"))

        tvStrengthHigh?.text = getString(R.string.common_strength_high_hint)
        tvStrengthMedium?.text = getString(R.string.common_strength_medium_hint)
        tvStrengthLow?.text = getString(R.string.common_strength_low_hint)
        tvStrengthInactive?.text = getString(R.string.common_strength_inactive_hint)

        tvStrengthHighValue?.text = ""
        tvStrengthMediumValue?.text = ""
        tvStrengthLowValue?.text = ""
        tvStrengthInactiveValue?.text = ""

        pieChartView?.setData(arrayListOf())

        getTheDayAcLevelData()
    }


    /**
     * 获取当天活动强度信息
     */
    fun getTheDayAcLevelData(){
        if (curTime <=0) return

        doOnIOThread {
            UserAcLevelRepo.instance.findByTimestampTheDay(curTime)?.let { originalListIt->
                //测试数据
//                val originalListIt :List<UserAcLevel> = JsonUtils.fromJsonList("[{\"createdTime\":1759334460000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759334460000,\"acLevel\":73},{\"createdTime\":1759335240000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759335240000,\"acLevel\":80},{\"createdTime\":1759335300000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759335300000,\"acLevel\":43},{\"createdTime\":1759335360000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759335360000,\"acLevel\":46},{\"createdTime\":1759339020000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759339020000,\"acLevel\":51},{\"createdTime\":1759339080000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759339080000,\"acLevel\":52},{\"createdTime\":1759340280000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759340280000,\"acLevel\":55},{\"createdTime\":1759342860000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759342860000,\"acLevel\":86},{\"createdTime\":1759344660000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759344660000,\"acLevel\":83},{\"createdTime\":1759348260000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759348260000,\"acLevel\":90},{\"createdTime\":1759348860000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759348860000,\"acLevel\":20},{\"createdTime\":1759380120000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1759380120000,\"acLevel\":52}]")

                if (originalListIt.isNullOrEmpty()) return@doOnIOThread

//                val listItStr = JsonUtils.toJson(originalListIt)

                var totalTime = 0L

                val groupedData = groupAcLevelDataByValueAndTime(originalListIt)

                groupedData.forEach { beanIt->
                    when (beanIt.status) {
                        80 -> strengthHigh += beanIt.timeLong
                        60 -> strengthMedium += beanIt.timeLong
                        30 -> strengthLow += beanIt.timeLong
                        0 -> strengthInactive += beanIt.timeLong
                    }
                    if (beanIt.status>=0){
                        totalTime += beanIt.timeLong
                    }
                }


                // 计算精确的百分比（保留小数）
                val strengthHighRatioExact = if (totalTime > 0) strengthHigh * 100.0 / totalTime else 0.0
                val strengthMediumRatioExact = if (totalTime > 0) strengthMedium * 100.0 / totalTime else 0.0
                val strengthLowRatioExact = if (totalTime > 0) strengthLow * 100.0 / totalTime else 0.0
                val strengthInactiveRatioExact = if (totalTime > 0) strengthInactive * 100.0 / totalTime else 0.0

                // 四舍五入到整数
                var strengthHighRatio = strengthHighRatioExact.toInt()
                var strengthMediumRatio = strengthMediumRatioExact.toInt()
                var strengthLowRatio = strengthLowRatioExact.toInt()
                var strengthInactiveRatio = strengthInactiveRatioExact.toInt()

                // 计算总和并调整最大值以确保总和为100%
                val currentSum = strengthHighRatio + strengthMediumRatio + strengthLowRatio + strengthInactiveRatio
                if (currentSum != 100 && totalTime > 0) {
                    val diff = 100 - currentSum
                    // 找到最大的比例值并调整
                    val maxValue = maxOf(strengthHighRatio, strengthMediumRatio, strengthLowRatio, strengthInactiveRatio)
                    when (maxValue) {
                        strengthHighRatio -> strengthHighRatio += diff
                        strengthMediumRatio -> strengthMediumRatio += diff
                        strengthLowRatio -> strengthLowRatio += diff
                        strengthInactiveRatio -> strengthInactiveRatio += diff
                    }
                }


                val chartData = listOf(
                    CusChartData(
                        createdTime = System.currentTimeMillis(),
                        mColor = ViewUtils.getColor(R.color.c_829fd9),
                        mProportion = strengthInactiveRatio.toFloat()
                    ),
                    CusChartData(
                        createdTime = System.currentTimeMillis(),
                        mColor = ViewUtils.getColor(R.color.c_ffcc66),
                        mProportion = strengthLowRatio.toFloat()
                    ),
                    CusChartData(
                        createdTime = System.currentTimeMillis(),
                        mColor = ViewUtils.getColor(R.color.c_ff9966),
                        mProportion = strengthMediumRatio.toFloat()
                    ),
                    CusChartData(
                        createdTime = System.currentTimeMillis(),
                        mColor = ViewUtils.getColor(R.color.c_ff6666),
                        mProportion = strengthHighRatio.toFloat()
                    ),
                )


                doOnUiThread {
                    tvStrengthHigh?.text = "${getString(R.string.common_strength_high_hint)} ${strengthHighRatio}%"
                    tvStrengthMedium?.text = "${getString(R.string.common_strength_medium_hint)} ${strengthMediumRatio}%"
                    tvStrengthLow?.text = "${getString(R.string.common_strength_low_hint)} ${strengthLowRatio}%"
                    tvStrengthInactive?.text = "${getString(R.string.common_strength_inactive_hint)} ${strengthInactiveRatio}%"

                    tvStrengthHighValue?.text = TimeUtils.formatTime((strengthHigh*60*1000), showHour = true, showMin = true)
                    tvStrengthMediumValue?.text = TimeUtils.formatTime((strengthMedium*60*1000), showHour = true, showMin = true)
                    tvStrengthLowValue?.text = TimeUtils.formatTime((strengthLow*60*1000), showHour = true, showMin = true)
                    tvStrengthInactiveValue?.text = TimeUtils.formatTime((strengthInactive*60*1000), showHour = true, showMin = true)

                    // 设置数据
                    pieChartView?.setData(chartData)
                }
            }
        }
    }
}